package cn.kent.high.questions.concurrentHashMap;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * {@link java.util.concurrent.ConcurrentHashMap}在高并发场景下使用不当 的用例
 * 场景实例：
 * - 在直播业务中，每个直播间对应一个topic，每个用户进入直播间时，会把自己的设备id绑定到这个topic上，也就是一个topic对应一堆设备id，
 * 可以使用map来维护 topic，设备id 的关联关系。
 * 以下代码模拟高并发下多个用户进入直播间
 */
public class TestMap1 {
    // 创建map，k为topic，v为设备id
    static ConcurrentHashMap<String, List<String>> map = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                List<String> list1 = new ArrayList<>();
                list1.add("device1");
                list1.add("device2");

                map.put("topic1", list1);
                System.out.println(JSON.toJSONString(map));
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                List<String> list1 = new ArrayList<>();
                list1.add("device11");
                list1.add("device22");

                map.put("topic1", list1);
                System.out.println(JSON.toJSONString(map));
            }
        });
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                List<String> list1 = new ArrayList<>();
                list1.add("device111");
                list1.add("device222");

                map.put("topic2", list1);
                System.out.println(JSON.toJSONString(map));
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();
        /**
         * 输出：
         * {"topic1":["device11","device22"],"topic2":["device111","device222"]}
         * {"topic1":["device11","device22"],"topic2":["device111","device222"]}
         * {"topic1":["device11","device22"],"topic2":["device111","device222"]}
         * 或
         * {"topic1":["device1","device2"],"topic2":["device111","device222"]}
         * {"topic1":["device1","device2"],"topic2":["device111","device222"]}
         * {"topic1":["device1","device2"],"topic2":["device111","device222"]}
         *
         */

    }

}
